package com.yubest.junit.encrypt.digest;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 摘要算法
 *
 * @Author: hweiyu
 * @Date: 2022/11/11 14:50
 */
public class Digest {

    private static final char[] c = "0123456789abcdef".toCharArray();

    private final String algorithm;

    public Digest(String algorithm) {
        this.algorithm = algorithm;
    }

    public byte[] digest(String data) {
        try {
            //获取MessageDigest对象
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            //在MD5算法这，得到的目标字节数组的特点：长度固定为16
            return digest.digest(data.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String digestHex(String data) {
        byte[] bytes = digest(data);
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            //取出b的高四位的值
            int high = (b & 0xF0) >> 4;
            //取出b的低四位的值
            int low = b & 0x0F;
            //以high为下标从 c 中取出对应的十六进制字符
            char highChar = c[high];
            //以low为下标从 c 中取出对应的十六进制字符
            char lowChar = c[low];
            buf.append(highChar).append(lowChar);
        }
        return buf.toString();
    }
}
